/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import fs from 'fs';
import path from 'path';
import { FileUtils } from "./fileUtils";

export let applicationInfoMap: Map<string, ApplicationInfo> = new Map();

export class FunctionUtils {
  static readApplicationsInfo(dir: string): Map<string, ApplicationInfo> {
    const applicationInfoMap: Map<string, ApplicationInfo> = new Map();
    const files: string[] = FileUtils.readFilesInDir(dir, (fileName) => {
      return fileName === "appInfo.txt"
    })
    if (files.length === 0) {
      return applicationInfoMap;
    }
    const applicationInfoFilePath = files[0]
    const fileContentArr: string[] = fs.readFileSync(applicationInfoFilePath, 'utf-8').split(/\r?\n/g);
    fileContentArr.forEach((fileContent: string) => {
      if (fileContent === '') {
        return;
      }
      const applicationStr: string[] = fileContent.split(' ');
      if (applicationStr.length < 2) {
        return;
      }
      const applicationInfoArr: string[] = applicationStr[1].split(',');
      const applicationInfo: ApplicationInfo = new ApplicationInfo()
      applicationInfo.setAppPath(applicationInfoArr[0]).setAppType(applicationInfoArr[1]);
      applicationInfoMap.set(applicationStr[0], applicationInfo);
    })
    return applicationInfoMap;
  }
  static setApplicationInfoMap(dir: string) {
    applicationInfoMap = FunctionUtils.readApplicationsInfo(dir);
  }
  static getBasicDirName() {
    return path.resolve(__dirname, '../../../');
  }
}
export class ApplicationInfo {
  appPath: string = '';
  appType: string = '';

  setAppPath(appPath: string): ApplicationInfo {
    this.appPath = appPath;
    return this;
  }

  getAppPath(): string {
    return this.appPath;
  }

  setAppType(appType: string): ApplicationInfo {
    this.appType = appType;
    return this;
  }

  getAppType(): string {
    return this.appType;
  }
}

